#include "simple_json.h"

#include <ctype.h>  // 添加ctype头文件
#include <assert.h> // Add assert.h header

char *remove_invisible_chars_exact(char *str)
{
    if (str == NULL)
        return NULL;

    int j = 0;
    for (int i = 0; str[i]; i++)
    {
        if (!iscntrl((unsigned char)str[i]) && str[i] != ' ')
        {
            str[j++] = str[i];
        }
    }
    str[j] = '\0';
    return str;
}
int mjson_parase(const char *_str, get_param_t *param, int len)
{
    const char *formats[TYPE_MAX] = {"%d", "%f", "%c"};

    char *str = remove_invisible_chars_exact((char *)_str);

    for (int i = 0; i < len; i++, param++)
    {
        char *target = strstr(str, param->key);
        if (NULL == target)
        {
            return -1;
        }

        target = strstr(target, "\":");
        if (NULL == target)
        {
            return -1;
        }
        sscanf(target + 2, formats[(int)param->type], param->data);

        // handle the bool type
        if (TYPE_BOOL == param->type)
        {
            if (*((char *)param->data) == 't' || *((char *)param->data) == 'T' || *((char *)param->data) == '1')
            {
                *((char *)param->data) = 1;
            }
            else if (*((char *)param->data) == 'f' || *((char *)param->data) == 'F' || *((char *)param->data) == '0')
            {
                *((char *)param->data) = 0;
            }
        }
    }
    return 0;
}

int mjson_get_int(const char *_str, const char *key, int *value)
{
    get_param_t param = {key, TYPE_INT, value};
    return mjson_parase(_str, &param, 1);
}

int mjson_get_float(const char *_str, const char *key, float *value){
    get_param_t param = {key, TYPE_FLOAT, value};
    return mjson_parase(_str, &param, 1);
}
int mjson_get_bool(const char *_str, const char *key, bool *value){
    get_param_t param = {key, TYPE_BOOL, value};
    return mjson_parase(_str, &param, 1);
}